package com.herui.ota.utils;

import com.mlnx.common.utils.MyLog;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class AccountLockManager {

    MyLog log = MyLog.getLog(getClass());

    private static final long TIME_WINDOW_MILLIS = 300000; // 5分钟的时间窗口
    private final ConcurrentHashMap<String, Long[]> accountFailures = new ConcurrentHashMap<>();

    private Set<String> lockAccountSet = new HashSet<>();

    // Long[0] = 错误次数, Long[1] = 最后错误时间戳
    public boolean recordFailure(String userId) {
        long now = System.currentTimeMillis();

        // 尝试获取用户的错误次数记录，如果不存在则创建新的
        Long[] info = accountFailures.computeIfAbsent(userId, k -> new Long[2]);

        if (info[1] == null){
            info[1] = now;
            info[0] = 0L;
        }

        // 检查是否超过时间窗口，如果是，则重置错误次数
        if (now - info[1] > TIME_WINDOW_MILLIS) {
            info[0] = 0L; // 重置错误次数
            info[1] = now; // 更新时间戳为当前时间
        } else {
            // 如果没有超过时间窗口，则增加错误次数
            info[0]++;
        }

        // 更新最后错误时间戳
        info[1] = now;

        // 检查是否达到错误次数阈值
        if (info[0] >= 5) {
            // 达到5次，处理屏蔽逻辑
            lockAccount(userId);
            accountFailures.remove(userId);
            return true;
        }

        return false;
    }

    public boolean isLock(String userId){
        return lockAccountSet.contains(userId);
    }

    public void unLock(String userId){
        accountFailures.remove(userId);
        lockAccountSet.remove(userId);
    }

    private void lockAccount(String userId) {
        log.info("Account " + userId + " has been locked due to too many failed login attempts.");
        // 这里可以添加更多逻辑，如将用户状态设置为锁定等
        lockAccountSet.add(userId);
    }

    public static void main(String[] args) {
        AccountLockManager accountLockManager = new AccountLockManager();
        accountLockManager.recordFailure("1");
    }
}

